import { cloneDeep } from 'lodash-es'
import { http } from '@/utils/http'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPlatformUser, getMoneyLimit } from '@/api/user'
import { checkRoles } from '@/stores/roles'
import _ from 'lodash-es'

export const useHomeStore = () => {
    const userStore = useUserStore()
    const state = reactive({
        schemeloading: false,
        schemeList: [],
        schemeActive: {},

        bctypes: [],
        groupList: [],
        activegroup: '',
        schemeorder: {},

        showtablelist: false,
        matchData: [],
        orderPage: {
            page: 1,
            page_size: 20,
            total: 0
        },

        saveorder: {
            list: [],
            total: 0,
            page: 1,
            page_size: 20,
            showloading: false,
            expand: ''
        },

        users: [],
        userId: null,
        platformUsers: null,
        userdialogshow: false,
        checkuserAll: false,
        radiouser: '',
        activecheckuserOrder: {},
        options: [],
        query: {
            platform_from: 'hga',
            select_type_from: 'event_type',
            event_type_from: 'today',
            league_from: 'all',
        },

        match: {
            loading: false,
            list: [],
            options: {},
            intervalId: null,
        },

        orderData: {
            type: 0, // 0、即时 1、预约

            match: null,

            list: {}, // 即时
            reservationList: {}, // 预约

            subscribe: {
                show: false,
            },
        },

        other: {
            data: null,
            match: null,
            otherType: null,
            intervalId: null,
            showAll: false,
        },

        orderInventory: {
            match: {},
            orderList: {},
            userId: ''
        },
        permissionBctypes: {},
        intervalId: null

    })

    const getschemeList = () => {
        let a = []
        let b = []
        clearInterval(state.intervalId)
        http.get('/scheme/scheme_list?page=1&page_size=999').then((res) => {
            res.data.list.forEach(item => {
                item.type = 0
            });
            a = res.data.list
            // state.schemeList = res.data.list
            // state.schemeloading = false
            http.get('/scheme/copy_scheme_list?page=1&page_size=999').then((res2) => {
                res2.data.list.forEach(item => {
                    item.type = 1
                });
                b = res2.data.list
                let result = mergeAndSortArrays(a, b);
                console.log(result);


                state.schemeList = result
                state.schemeloading = false
                clearInterval(state.intervalId)
                state.intervalId = setInterval(() => getschemeList(), 5000)
            }).catch(() => {
                state.schemeloading = false
            })
        }).catch(() => {
            state.schemeloading = false
        })
    }

    function mergeAndSortArrays(arr1, arr2) {
        // 合并两个数组
        const mergedArray = [...arr1, ...arr2];

        // 按照 create_time 字段进行排序
        mergedArray.sort((a, b) => {
            const timeA = new Date(a.creat_time);
            const timeB = new Date(b.creat_time);
            return timeB - timeA;  // 升序排序
        });

        return mergedArray;
    }

    const changeschemeActive = (row) => {
        state.schemeActive = row
        state.orderPage = {
            page: 1,
            page_size: 20,
            total: 0
        }
        state.saveorder = {
            list: [],
            total: 0,
            page: 1,
            page_size: 20,
            showloading: false,
            expand: ''
        }
        getmatchData()
        getorderlist()
    }

    const getbctypes = () => {
        http.get('/config/get_bc_type', { params: { page: 1, page_size: 999, status: 1 } }).then((res) => {
            state.bctypes = res.data.out_platform.map(item => {
                return {
                    value: item.bc_type,
                    label: item.name,
                    isLogin: 0,
                    formData: {
                        user_name: '',
                        pass_word: '',
                        group_id: '',
                        ip: ''
                    }
                }
            })
            console.log(state.bctypes);

        })
    }

    const getGrouplist = () => {
        http.get('/group/group_list', {
            params: {
                page: 1,
                page_size: 9999,
                status: 1
            }
        }).then(res => {
            state.groupList = res.data.list.map(item => {
                return { value: item.id, label: item.name }
            })
            state.userId = state.groupList.length > 0 ? state.groupList[0].value : ''
        })
    }

    const clicklogin = (row) => {

        if (row.formData.user_name != '' && row.formData.pass_word != '' && row.formData.group_id != '') {
            row.isLogin = 2
            let body = JSON.parse(JSON.stringify(row.formData))
            body.bc_type = row.value
            if (body.ip == '') {
                delete body.ip
            }
            console.log(body);

            http.post('/member/member_login', body).then((res) => {
                console.log(res);
                row.isLogin = 0

            }).catch(() => {
                row.isLogin = 0
            })

        } else {
            ElMessage.error('请完善字段')
        }



    }

    const getmatchData = () => {
        state.showtablelist = true
        let params = {
            page: state.orderPage.page,
            page_size: state.orderPage.page_size,
            scheme_code: state.schemeActive.scheme_code
        }
        if (state.schemeActive.type == 0) {
            http.get(`/match/match_list_by_scheme`, { params }).then((res) => {
                state.showtablelist = false
                state.matchData = res.data.list
                state.orderPage.page = res.data.page
                state.orderPage.page_size = res.data.page_size
                state.orderPage.total = res.data.total
            })
        } else {
            http.get(`/match/match_list_by_copy_scheme`, { params }).then((res) => {
                state.showtablelist = false
                state.matchData = res.data.list
                state.orderPage.page = res.data.page
                state.orderPage.page_size = res.data.page_size
                state.orderPage.total = res.data.total
            })
        }

    }

    const clickMatchRow = async (row) => {
        if (checkRoles(userStore.user.roles, 'hand_copy')) {
            state.schemeorder = row
            await getUserConfig()
            console.log(state.orderData.match?.ids != row.ids);

            if (state.orderData.match?.ids != row.ids) {
                state.orderData.list = {}
                state.orderData.reservationList = {}
                state.orderData.match = cloneDeep(row)
            }
            http
                .post(`/match/other_platform_odd_list`, {
                    bc_type: row.from_bc_type,
                    league_id: row.minfo.league_id,
                    home_id: row.minfo.home_id,
                    away_id: row.minfo.away_id,
                    pk_odds_key: row.pk_odds_key,
                    event_type: row.event_type,
                    sport_type: row.sport_type
                    //   nav_data: item.nav_data,
                    //   odd: item.odd,
                })
                .then(res => {
                    let a = []

                    res.data.forEach(item => {
                        state.permissionBctypes.forEach(item2 => {
                            if (item.bc_type == item2.value) {
                                a.push(item)
                            }
                        });
                    });


                    a.min_odd = a.odd
                    a.max_odd = 1000

                    a.map(item => {
                        item.checked = false
                        item.direction = 'zheng'
                    })
                    // a.forEach(item => {

                    // });

                    // state.orderData.match.sport_type = res.data[0].nav_data.sportType == 1 ? 'soccer' : 'basketball'
                    state.orderData.match.sport_type = row.sport_type
                    state.orderData.list[row.pk_odd_key] = _.cloneDeep(a)
                    state.orderData.reservationList[row.pk_odd_key] = _.cloneDeep(a)
                    console.log(state.orderData);


                })
        }


    }

    const handlePageChange = () => {
        getmatchData()
    }

    const bctypeLabel = (value) => {
        let a = ''
        state.bctypes.forEach(item => {
            if (item.value == value) {
                a = item.label
            }
        });
        return a
    }

    const getorderlist = () => {
        state.saveorder.showloading = true
        let body = {
            page: state.saveorder.page,
            page_size: state.saveorder.page_size,
            scheme_task_code: state.schemeActive.scheme_code
        }
        http.post(`/order/order_list_byscheme`, body).then((res) => {
            state.saveorder.list = res.data.order_list
            state.saveorder.total = res.data.total
            state.saveorder.page = res.data.page
            state.saveorder.page_size = res.data.page_size
            state.saveorder.showloading = false

        })
    }


    const getUserConfig = () => {
        if (!state.userId) return

        getPlatformUser({ id: state.userId }).then(res => {
            console.log(res);

            state.platformUsers = res.data

        })
    }
    const onChangeUser = async () => {
        const list = state.orderData.type == 0 ? state.orderData.list : state.orderData.reservationList

        for (let i = 0; i < list.length; i++) {
            const orders = list[i]

            for (let i = 0; i < orders.length; i++) {
                const order = orders[i]

                order.max_stake = res.data.max_stake
                order.min_stake = res.data.min_stake
                order.odd = res.data.odd
            }
        }

        await getUserConfig()
    }

    function getOrderInfo(order) {
        let body = {
            member_id: order.userId,
            user_type: 'member',
            nav_data: order.nav_data,
            pk_odds_key: order.pk_odds_key,
        }

        getMoneyLimit(body)
            .then(res => {
                console.log(res);

                order.max_stake = res.data.max_stake
                order.min_stake = res.data.min_stake
                order.odd = res.data.odd
            })
            .catch(() => {
                order.max_stake = null
                order.min_stake = null
            })
    }

    const showSubscribe = data => {
        state.orderData.subscribe.data = data
        state.orderData.subscribe.show = true
    }

    const changeOrdermode = (order) => {
        order.place_mode = ''
    }




    onMounted(async () => {
        initData()
    })

    onUnmounted(() => {
        clearInterval(state.intervalId)
      })


    async function initData() {
        state.schemeloading = true
        getschemeList()
        getbctypes()
        getGrouplist()
    }


    return {
        state,

        changeschemeActive,
        handlePageChange,
        clicklogin,
        clickMatchRow,
        bctypeLabel,
        getUserConfig,
        getOrderInfo,
        showSubscribe,
        getorderlist,
        changeOrdermode,
        onChangeUser

    }
}
